package com.ybkj.daijia.api.member.v3;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.api.driver.SecurityUtils;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandUpService;
import com.ybkj.daijia.server.service.MemberService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author bo
 */
@Controller("MemberErrandUpV3Controller")
@RequestMapping(value = "member/api/rest/v3/up")
public class ErrandUpController {

    private static final Logger logger = LoggerFactory.getLogger(ErrandUpController.class);

    @Autowired
    private ErrandUpService errandService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private DriverService driverService;

    @RequestMapping(value = "getPaotuiAreaInfo")
    public @ResponseBody
    ResultTransport getPaotuiAreaInfo(Long passengerId, String city, String appKey, String token,
        String timestamp) {

        logger
            .debug("recv passengerId:{},city:{},appKey:{},token:{},timestamp:{}", passengerId, city,
                appKey, token, timestamp);

        if (null == passengerId || StringUtils.isBlank(city) || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(passengerId));
        params.add(city);
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Passenger passenger = memberService.findOnePassenger(passengerId);

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS);
        }

        try {

            Area area = null;

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

            Company finalCompany = null;//最终决定公司

            Area paotuiArea = null;
            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                paotuiArea = areaService.findPaotuiByPassenger(passenger.getId());
            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                paotuiArea = areaService.findPaotuiByEnterprise(passenger.getEnterprise_id());
            }

            if (null != paotuiArea) {
                area = areaService.findOneWithCharge(paotuiArea.getId());
            } else {
                List<Company> companys = companyService.findByAreaCityName(city);
                if (!CollectionUtils.isEmpty(companys)) {
                    for (Company company : companys) {
                        if (company.getId().equals(passenger.getCompanyId())) {
                            finalCompany = company;
                            break;
                        }
                    }

                    List<Company> notMainCompanys = new ArrayList<Company>();
                    Company cityMainCompany = null;

                    if (null == finalCompany) {
                        for (Company company : companys) {
                            if (!company.isCompanyType()) {
                                notMainCompanys.add(company);
                            } else {
                                cityMainCompany = company;
                            }
                        }
                        if (!CollectionUtils.isEmpty(notMainCompanys)) {
                            finalCompany = notMainCompanys
                                .get(new Random().nextInt(notMainCompanys.size()));
                        }
                    }

                    if (null == finalCompany) {
                        if (null != cityMainCompany) {
                            finalCompany = cityMainCompany;
                        }
                    }

                }

                if (null == finalCompany) {
                    finalCompany = companyService.findOne(passenger.getCompanyId());
                }

                area = areaService.findOneWithCharge(finalCompany.getAreaPaotuiId());
            }

            instance.setData(area);

            return instance;

        } catch (Exception e) {
            logger.error("api v3 errand getPaotuiAreaInfo error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    /**
     * 查询单个司机
     *
     * @param driverId
     * @return
     */
    @RequestMapping(value = "queryDriver")
    public @ResponseBody
    Map<String, Object> queryDriver(Long driverId) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (null != driverId) {
            Driver driver = driverService.findOne(driverId);
            if (null != driver) {
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("employAddress", driver.getAddress());
                data.put("employPhone", driver.getPhone());
                data.put("employLat", driver.getLastLatitude());
                data.put("employLng", driver.getLastLongitude());

                map.put("code", 0);
                map.put("data", data);
                map.put("message", "查询成功");
            } else {
                map.put("code", -5);
                map.put("message", "服务人员不存在");
            }
        } else {
            map.put("code", -1);
            map.put("message", "参数错误");
        }
        return map;
    }

    /**
     * 筛选公司
     *
     * @param acKey
     * @param companyId
     * @param longitude
     * @param latitude
     * @return
     */
    @RequestMapping(value = "getCompany", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> getCompany(
        @RequestParam(required = false, value = "acKey") String acKey,
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "longitude") Double longitude,
        @RequestParam(required = false, value = "latitude") Double latitude) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Company companyByAppKey = null;
            if (StringUtils.isNotBlank(acKey)) {
                companyByAppKey = companyService.findByAppKey(acKey);
            }
            if (companyByAppKey == null && longitude != null && latitude != null) {
                String city = "";

                List<Company> companyList = null;
                int i = 0;
                while (i <= 4) {
                    city = HttpClientUtil.getCityByLngAndLat(longitude, latitude);
                    if (StringUtils.isNotBlank(city)) {
                        break;
                    }
                    i++;
                }
                companyList = companyService.findByAreaCityName(city);
                if (!CollectionUtils.isEmpty(companyList)) {

                    if (null != companyId) {
                        for (Company c : companyList) {
                            if (c.getId().equals(companyId)) {
                                companyByAppKey = c;
                                break;
                            }
                        }
                    }

                    List<Company> notMainCompanys = new ArrayList<Company>();//子公司
                    if (companyByAppKey == null) {
                        for (Company c : companyList) {
                            if (!c.isCompanyType()) {
                                if (StringUtils.isBlank(c.getAppKey())) {
                                    notMainCompanys.add(c);
                                }
                            }
                        }
                        if (!CollectionUtils.isEmpty(notMainCompanys)) {
                            companyByAppKey = notMainCompanys
                                .get(new Random().nextInt(notMainCompanys.size()));
                        }
                    }
                }
            }

            if (companyByAppKey == null) {
                companyByAppKey = companyService.getMain();
            }

            map.put("code", 0);
            map.put("message", "成功");
            map.put("data", companyByAppKey.getId());
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", -1);
            map.put("message", "查询失败");
            map.put("data", null);
        }
        return map;
    }

    /**
     * 筛选公司返回id和名称
     *
     * @param acKey
     * @param companyId
     * @param longitude
     * @param latitude
     * @return
     */
    @RequestMapping(value = "getCompanyIdAndName", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> getCompanyIdAndName(
        @RequestParam(required = false, value = "acKey") String acKey,
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "longitude") Double longitude,
        @RequestParam(required = false, value = "latitude") Double latitude) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Company companyByAppKey = null;
            if (StringUtils.isNotBlank(acKey)) {
                companyByAppKey = companyService.findByAppKey(acKey);
            }
            if (companyByAppKey == null && longitude != null && latitude != null) {
                String city = "";

                List<Company> companyList = null;
                int i = 0;
                while (i <= 4) {
                    city = HttpClientUtil.getCityByLngAndLat(longitude, latitude);
                    if (StringUtils.isNotBlank(city)) {
                        break;
                    }
                    i++;
                }
                companyList = companyService.findByAreaCityName(city);
                if (!CollectionUtils.isEmpty(companyList)) {
                    for (Company c : companyList) {
                        if (null != companyId && c.getId().equals(companyId)) {
                            companyByAppKey = c;
                            break;
                        }
                    }
                    List<Company> notMainCompany = new ArrayList<Company>();//子公司
                    if (companyByAppKey == null) {
                        for (Company c : companyList) {
                            if (!c.isCompanyType()) {
                                if (StringUtils.isBlank(c.getAppKey())) {
                                    notMainCompany.add(c);
                                }
                            }
                        }
                    }
                    if (companyByAppKey == null && notMainCompany != null
                        && notMainCompany.size() != 0) {
                        companyByAppKey = notMainCompany
                            .get(new Random().nextInt(notMainCompany.size()));
                    }
                }
            }

            if (companyByAppKey == null) {
                companyByAppKey = companyService.getMain();
            }

            Map<String, Object> m = new HashMap<String, Object>();
            m.put("companyId", companyByAppKey.getId());
            m.put("companyName", companyByAppKey.getAbbreviation());
            m.put("areaId", companyByAppKey.getAreaId());

            map.put("code", 0);
            map.put("message", "成功");
            map.put("data", m);

        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", -1);
            map.put("message", "查询失败");
            map.put("data", null);
        }
        return map;
    }

    /**
     * 预算费用
     *
     * @param areaId
     * @param time
     * @param mileage
     * @return
     */
    @RequestMapping(value = "getNewPrice")
    public @ResponseBody
    Map<String, Object> getNewPrice(
        @RequestParam(required = true, value = "areaId") Long areaId,
        @RequestParam(required = true, value = "areaWeightId") Long areaWeightId,
        @RequestParam(required = false, value = "weight") Double weight,
        @RequestParam(required = false, value = "time") Integer time,
        @RequestParam(required = false, value = "mileage") Double mileage) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (null == mileage) {
                mileage = 0.0;
            }
            if (null == time) {
                time = 0;
            }
            if (null == weight) {
                weight = 0.0;
            }
            Map<String, Object> map2 = errandService.getNewPrice(areaId, mileage, time);
            Map<String, Object> map3 = errandService.getNewWeightPrice(areaWeightId, weight);
            if ((Boolean) map2.get("success") && (Boolean) map3.get("success")) {
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("money", map2.get("money"));
                data.put("startPrice", map2.get("startPrice"));
                data.put("mileagePrice", map2.get("mileagePrice"));
                data.put("travelTimePrice", map2.get("travelTimePrice"));
                data.put("weightPrice", map3.get("money"));
                data.put("pay_detail",
                    map2.get("pay_detail").toString() + "\n" + map3.get("pay_detail").toString());
                map.put("data", data);
                map.put("message", map2.get("message"));
                map.put("code", 0);
            } else {
                map.put("code", -42);
                map.put("message", "请求失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", -42);
            map.put("message", "预算失败");
        }
        return map;
    }

}
